package com.demo.lifeinfo.common.home.fm;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.demo.lifeinfo.R;
import com.demo.lifeinfo.adapter.MyNineImageAdapter;
import com.demo.lifeinfo.app.XBaseFragment;
import com.demo.lifeinfo.common.mine.PersonalnfoAc;
import com.demo.lifeinfo.common.news.NewsDetailAc;
import com.demo.lifeinfo.common.sign.LoginActivity;
import com.demo.lifeinfo.entity.News;
import com.demo.lifeinfo.entity.Tab;
import com.demo.lifeinfo.entity.User;
import com.demo.lifeinfo.model.GlideApp;
import com.demo.lifeinfo.widget.CustomPopup;
import com.google.android.material.tabs.TabLayout;
import com.jaeger.ninegridimageview.NineGridImageView;
import com.lxj.xpopup.XPopup;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobPointer;
import cn.bmob.v3.datatype.BmobRelation;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.UpdateListener;

/**
 * created by Raymond
 * on 2019-04-24
 */
public class HomeFm extends XBaseFragment {
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.smartLayout)
    SmartRefreshLayout smartLayout;

    BaseQuickAdapter<News, BaseViewHolder> adapter;
    @BindView(R.id.tablayout)
    TabLayout tablayout;


    List<Tab> tabs;
    @BindView(R.id.toolbar_back)
    ImageView toolbarBack;
    @BindView(R.id.textView3)
    TextView textView3;


    public static HomeFm newInstance() {
        Bundle args = new Bundle();
        HomeFm fragment = new HomeFm();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fm_home;
    }

    @Override
    public void initView() {
        toolbarBack.setVisibility(View.GONE);
        textView3.setText("百科生活");
        tabs = new ArrayList<>();
        tabs.add(new Tab("全部"));
        tabs.add(new Tab("热门"));
        tabs.add(new Tab("推荐"));
        tabs.add(new Tab("问题"));
        tabs.add(new Tab("趣事"));
        tabs.add(new Tab("其他"));

        for (Tab tab : tabs) {
            tablayout.addTab(tablayout.newTab().setText(tab.getTitle()));
        }
        tablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab.getPosition() > 2) {
                    getData(tab.getPosition() - 2);
                } else if (tab.getPosition() == 0) {
                    getData(0);
                } else if (tab.getPosition() == 1) {
                    getHot();
                } else if (tab.getPosition() == 2) {
                    getRecommend();
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        adapter = new BaseQuickAdapter<News, BaseViewHolder>(R.layout.item_product) {
            @Override
            protected void convert(BaseViewHolder helper, News item) {
                NineGridImageView nineGridImageView = helper.getView(R.id.nindImgView);
                MyNineImageAdapter imageAdapter = new MyNineImageAdapter();
                nineGridImageView.setAdapter(imageAdapter);
                nineGridImageView.setImagesData(item.getImgs());
                GlideApp.with(getActivity())
                        .load(item.getAuthor().getAvatar() == null ? R.drawable.ic_launcher_background : item.getAuthor().getAvatar().getFileUrl())
                        .centerCrop()
                        .placeholder(R.mipmap.ic_launcher)
                        .error(R.mipmap.ic_launcher)
                        .circleCrop()
                        .into((ImageView) helper.getView(R.id.circleImageView));
                helper.setText(R.id.textView, TextUtils.isEmpty(item.getAuthor().getNickeName()) ? "匿名" : item.getAuthor().getNickeName());
                helper.setText(R.id.expandable_text, item.getContent());
                helper.setVisible(R.id.btn_look, item.getContent().length() > 80 ? true : false);
                helper.addOnClickListener(R.id.btn_look);
                helper.addOnClickListener(R.id.circleImageView);

            }
        };
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.view_empty, null);
        adapter.setEmptyView(view);
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                News news = (News) adapter.getItem(position);
                if (view.getId() == R.id.btn_look) {
                    new XPopup.Builder(getActivity())
                            .asCustom(new CustomPopup(getActivity(), news.getContent()))
                            .show();
                } else if (view.getId() == R.id.circleImageView) {
                    Intent intent = new Intent(getActivity(), PersonalnfoAc.class);
                    intent.putExtra("user", news.getAuthor());
                    startActivity(intent);
                }
            }
        });
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                News news = (News) adapter.getItem(position);
                Intent intent = new Intent(getActivity(), NewsDetailAc.class);
                intent.putExtra("news", news);
                startActivity(intent);
            }
        });
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setAdapter(adapter);
        smartLayout.setEnableLoadMore(false);
        smartLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                getData(0);
            }
        });

    }

    @Override
    public void initData() {
        smartLayout.autoRefresh();
    }

    private void getData(int type) {

        BmobQuery<News> query = new BmobQuery<>();

        if (type > 0) {
            showProgressDialog();
            query.order("-createdAt").include("author").addWhereEqualTo("type", type).findObjects(new FindListener<News>() {
                @Override
                public void done(List<News> list, BmobException e) {
                    dimssProgressDialog();
                    if (e == null) {
                        adapter.setNewData(list);
                    } else {
                        showError(e.getMessage());
                    }
                }
            });
        } else {
            query.order("-createdAt").include("author").findObjects(new FindListener<News>() {
                @Override
                public void done(List<News> list, BmobException e) {
                    smartLayout.finishRefresh();
                    if (e == null) {
                        adapter.setNewData(list);
                    } else {
                        showError(e.getMessage());
                    }
                }
            });
        }

    }

    private void getHot() {
        showProgressDialog();
        BmobQuery<News> query = new BmobQuery<>();
        query.order("-liks").include("author").findObjects(new FindListener<News>() {
            @Override
            public void done(List<News> list, BmobException e) {
                dimssProgressDialog();
                if (e == null) {
                    adapter.setNewData(list);
                } else {
                    showError(e.getMessage());
                }
            }
        });
    }

    private void getRecommend() {
//        showProgressDialog();
        if (!BmobUser.isLogin()) {
            getData(0);
        } else {
            User user22 = BmobUser.getCurrentUser(User.class);
            if (user22.getHobby() != null && user22.getHobby().size() > 0) {
                BmobQuery<News> query = new BmobQuery<>();
                query.addWhereContainedIn("tag", user22.getHobby()).include("author").order("-createdAt").findObjects(new FindListener<News>() {
                    @Override
                    public void done(List<News> list, BmobException e) {
                        if (e == null) {
                            adapter.setNewData(list);
                        } else {
                            showError(e.getMessage());
                        }
                    }
                });

            }
        }


    }

    List<String> testData() {
        List<String> data = new ArrayList<>();
//        data.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1556104617149&di=beb03ff81c8665c37f52f1980d33643f&imgtype=0&src=http%3A%2F%2Fwww.62a.net%2Ftbimg%2Fimg02%2Fbao%2Fuploaded%2Fi2%2F373980990%2FTB2xd9CeQ1M.eBjSZPiXXawfpXa_%2521%2521373980990.jpg_290x290.jpg");
//        data.add("https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=1358912637,650406261&fm=26&gp=0.jpg");
        data.add("https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=1358912637,650406261&fm=26&gp=0.jpg");
        return data;
    }
}
